<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <h1>websocket前后端通信</h1>
  <p id="receive"></p>
  <input id="ipt" /><button id="btn">发送</button>

  <script>
    var ws = new WebSocket('ws://localhost:5000/test');
    console.log("ws", ws)

    // 打开WebSocket连接后立刻发送一条消息:
    ws.onopen = function () {
      console.log('1.连接成功');
      // ws.send('Hello!');
    };

    // 响应收到的消息:
    ws.onmessage = function (message) {
      console.log("响应收到的消息", message)
      document.getElementById('receive').innerHTML = "响应收到的消息: "+message.data;

      // 做一些事情
      doSomething()

      // 回复服务器
      // ws.send('收到'+Date.now())
    }

    function doSomething(){
      setTimeout(()=>{
        console.log('前端做完处理了')
        // 告诉服务器
        let obj={
          status: 0,
          data: 'front finish'
        }
        ws.send(JSON.stringify(obj))
      }, 3000)
    }

    let ipt = document.getElementById('ipt')
    let btn = document.getElementById('btn')
    btn.onclick=function(){
      ws.send(ipt.value)
    }
  </script>
</body>

</html>